﻿using LibraryMangementSystem.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LibraryMangementSystem.BookRental
{
    public partial class ReturnBook : Form
    {
        public ReturnBook()
        {
            InitializeComponent();
        }

        private void button_loan_Click(object sender, EventArgs e)
        {
            if (textBox_bookId.Text != "" && textBox_certId.Text != "")
            {
                LibraryEntities1 library = new LibraryEntities1();
                /*library.Loan*/
                Loan loan = new Loan();
                loan.BookID = textBox_bookId.Text;
                loan.Cert_id = textBox_certId.Text;
                loan.Loandates = BookUtil.Format_date(dateTimePicker_loanDate.Value);
                loan.Return = BookUtil.Format_date(DateTime.Now);
                //将要修改的对象放入上下文对象中
                library.Loan.Attach(loan);

                IQueryable<Loan> IQueryable_loan = library.Loan.Where<Loan>(L => L.BookID == loan.BookID && L.Cert_id == loan.Cert_id && L.Loandates == loan.Loandates);
                long sum = IQueryable_loan.LongCount();

                if (sum == 0)
                {
                    MessageBox.Show("没有此借书证信息，或者借书证ID填写错误\n");
                    return;
                }

                Loan query_loan = IQueryable_loan.FirstOrDefault();
                if (query_loan.Return < loan.Return)
                {
                    MessageBox.Show("已超时");
                    return;
                }

                Loan loans = library.Loan.Single(L => L.BookID == loan.BookID && L.Cert_id == loan.Cert_id && L.Loandates == loan.Loandates);
                loans.flag = 0;
                string str;
                int i = library.SaveChanges();
                if (i != 1)
                {
                    str = "还书失败,您已还过此书了";
                    MessageBox.Show(str);
                    return;
                }

                //加库存
                BookUtil.addStock(loans.BookID, library);
                //加借书次数
                BookUtil.addCert(loans.Cert_id, library);
                str = "还书成功";
                MessageBox.Show(str);




            }
        }
    }
}
